package game.map
{
	import game.manager.ConfigurationManager;
	import game.manager.TextureManager;
	import game.VO.TileTemplateVO;
	import game.VO.TileVO;
	import starling.display.Image;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.events.EventDispatcher;
	import starling.textures.Texture;
	
	/**
	 * ...
	 * @author Kirill Pletnev
	 */
	public class Tile extends EventDispatcher
	{
		private var _container:Sprite;
		private var _tileVO:TileVO;
		private var _tileImage:Image;
		
		public function Tile(container:Sprite, tileVO:TileVO)
		{
			_container = container;
			_tileVO = tileVO;
		}
		
		public function setTileOnMap():void
		{
			var templateTileVO:TileTemplateVO = _tileVO.getTileTemplateVO(_tileVO.tileTemplateID);
			TextureManager.instance.load(ConfigurationManager.instance.pathToTileRes + templateTileVO.textureURL, onTextureLoad);
		}
		
		public function removeTileFromMap():void
		{
			_container.removeChild(_tileImage);
		}
		
		public function onTextureLoad(tileTexture:Texture):void
		{
			tileTexture.repeat = false;
			
			_tileImage = new Image(tileTexture);			
			_tileImage.dispose();			
			_tileImage.x = VisualMap.getX(_tileVO.columnPosition, _tileVO.rowPosition);
			_tileImage.y = VisualMap.getY(_tileVO.columnPosition, _tileVO.rowPosition);
			_tileImage.width = ConfigurationManager.instance.tileWidth;
			_tileImage.height = ConfigurationManager.instance.tileHeight;
			_tileImage.pivotX = ConfigurationManager.instance.tileHalfWidth;
			
			_container.addChild(_tileImage);
			
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function toString():String
		{
			return "[Tile where tileVO = " + _tileVO.toString() + " ]";
		}
	}

}